<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :exclude-values="['userCName', 'groupCname', 'endTime']"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
      @reset="resetClick"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processKey" label="流程名称">
          <ProcessName v-model="state.query.processKey"></ProcessName>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startId" label="流程发起人">
          <!-- <FIInput v-model="state.query.startId" clearable /> -->
          <FIAutoInput
            v-model="state.query.userCName"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'fqr')"
            @change="changeEvent($event, 'fqr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="startTime" label="流程发起时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <!-- <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="endTime" label="至">
          <FIDatePicker
            value-format="YYYY-MM-DD"
            v-model="state.query.endTime"
            type="date"
            placeholder="流程结束时间"
            clearable
          />
        </FIFormItem>
      </el-col> -->
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="groupByDateType" label="导出数据时间类型">
          <FISelect
            v-model="state.query.groupByDateType"
            valueCustom="value"
            :options="[
              {
                value: '',
                label: '不按时间区间统计',
              },
              {
                value: 'month',
                label: '按月统计',
              },
              {
                value: 'day',
                label: '按天统计',
              },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="流程效率统计记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="processDefKey"
      :showSaveModel="false"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
    <FIModel v-model="proccessShow" title="任务查询列表" @close="proccessShow = false">
      <el-row :gutter="20">
        <el-col :span="6" class="flex-center">
          <FIFormItem label="流程定义">
            <FIInput v-model="processDefKey" clearable disabled />
          </FIFormItem>
        </el-col>
        <el-col :span="6" class="flex-center">
          <FIFormItem label="流程名称">
            <FIInput v-model="processName" clearable disabled />
          </FIFormItem>
        </el-col>
      </el-row>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="detailList"
        :showSaveModel="false"
        :rowNo="true"
        v-model:columns="columns1"
        :insertable="false"
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :settingConfig="settingConfig"
        :pageConfig="pageConfig1"
        primaryKey="activityDefKey"
        @table-refresh="searchFn"
        @size-change="handleSizeChange1"
        @current-page-change="handleCurrentChange1"
        @action-click="nodeActionClick"
      >
      </FITable>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <FIButton @click="proccessShow = false">关闭</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
    <FIModel v-model="nodeShow" title="经办查询列表" @close="nodeShow = false">
      <el-row :gutter="20">
        <el-col :span="6" class="flex-center">
          <FIFormItem label="节点定义">
            <FIInput v-model="activityDefKey" clearable disabled />
          </FIFormItem>
        </el-col>
        <el-col :span="6" class="flex-center">
          <FIFormItem label="节点名称">
            <FIInput v-model="activityName" clearable disabled />
          </FIFormItem>
        </el-col>
      </el-row>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="nodeList"
        primaryKey="processDefKey"
        :showSaveModel="false"
        :rowNo="true"
        v-model:columns="columns2"
        :insertable="false"
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig2"
        :settingConfig="settingConfig"
        @size-change="handleSizeChange2"
        @current-page-change="handleCurrentChange2"
      >
      </FITable>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <FIButton @click="nodeShow = false">关闭</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import ProcessName from '../../components/ProcessName.vue'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryProccessCount,
  apiDeleteAuth,
  apiQueryProcessesDef,
  apiQueryAllBpmCatogary,
  apiQueryProccessActivity,
  apiQueryProccessActivityTask,
  apiExportCount,
  apiQueryDept,
  apiQueryUser,
} from '@/api/modules/EW.js'
import DeptTree from '../../components/DeptTree'
const route = useRoute()
const processPage = ref(1)
const searchWrapperSpan = 8
const loadMoreEnd = ref(false)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'processDefKey'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const proccessShow = ref(false)
const nodeShow = ref(false)
const tableRef = ref(null)
const deptList = ref([])
const userList = ref([])
const detailList = ref([])
const nodeList = ref([])
const processDefKey = ref('')
const activityDefKey = ref('')
const processName = ref('')
const activityName = ref('')
const state = reactive({
  query: {
    processKey: '',
    startId: '',
    startTime: '',
    endTime: '',
    startDeptId: '',
    groupByDateType: '',
    userCName: '',
    groupCname: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const pageConfig1: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const pageConfig2: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const columns1: Column[] = reactive([
  {
    label: '节点定义',
    prop: 'activityDefKey',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '节点名称',
    prop: 'activityName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '节点实例数',
    prop: 'processNodeNum',
    sortable: true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（小时）',
    prop: 'activityAvgDuration',
    sortable: true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'node_detail', type: 'top' }],
  },
])
const columns2: Column[] = reactive([
  {
    label: '经办人ID',
    prop: 'completerId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人名称',
    prop: 'completerFullname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门ID',
    prop: 'deptEname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人部门名称',
    prop: 'deptCname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '经办人任务数',
    sortable: true,
    prop: 'processTaskNum',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（小时）',
    sortable: true,
    prop: 'taskAvgDuration',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
const columns: Column[] = reactive([
  {
    label: '流程定义',
    prop: 'processDefKey',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程实例数',
    sortable: true,
    prop: 'processInsNum',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（小时）',
    sortable: true,
    queryName:'PROCESS_AVG_DURATION',
    prop: 'avgDuration',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'detail', type: 'top' }],
  },
])

const checkedRows = ref([])
const processArr = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
//重置
const resetClick = () => {
  state.query.startId = ''
  state.query.startDeptId = ''
  state.query.userCName = ''
  state.query.groupCname = ''
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleSizeChange1 = (e) => {
  pageConfig1.pageSize = e
  pageConfig1.currentPage = 1
  getList1()
}
const handleSizeChange2 = (e) => {
  pageConfig2.pageSize = e
  pageConfig2.currentPage = 1
  getList2()
}
const changeEvent = (e, type) => {
  if (!e) {
    if (type == 'fq_dept') state.query.startDeptId = ''
    if (type == 'fqr') state.query.startId = ''
  }
}
const selectClick = (data, type) => {
  console.log(data, type, 'data123')
  if (type == 'fqr') {
    state.query.startId = data.loginName
  } else {
    state.query.startDeptId = data.groupEname
  }
}
//导出
const exportClick = () => {
  apiExportCount(state.query)
}
//删除事件
// const deleteRow = () => {
//   if (!checkedRows.value.length) {
//     useMessage().warning('请选择一条数据')
//     return
//   }
//   let ids = []
//   Array.isArray(checkedRows.value) &&
//     checkedRows.value.forEach((item: any) => {
//       if (item?.id) ids.push(item?.id)
//     })
//   isTableLoading.value = true
//   apiDeleteAuth(ids)
//     .then((res) => {
//       isTableLoading.value = false
//       if (res.data.success) {
//         useMessage().success(res.data.message)
//         searchFn()
//       }
//     })
//     .catch((error: any) => {
//       useMessage().error(error.data.message)
//       isTableLoading.value = false
//     })
// }
const nodeActionClick = (item, rowData, btnInfo) => {
  activityDefKey.value = rowData.activityDefKey
  activityName.value = rowData.activityName
  getList2()
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  processDefKey.value = rowData.processDefKey
  processName.value = rowData.processName
  getList1()
}
const getList1 = () => {
  let par = {
    current: pageConfig1.currentPage,
    size: pageConfig1.pageSize,
    processDefKey: processDefKey.value,
    startTime: state.query.startTime,
    endTime: state.query.endTime,
    startDeptId: state.query.startDeptId,
    groupByDateType: state.query.groupByDateType,
    startId: state.query.startId,
  }
  apiQueryProccessActivity(par)
    .then((res) => {
      if (res.data.success) {
        proccessShow.value = true
        detailList.value = res.data.data.result

        pageConfig1.pageSize = Number(res.data.data.size)
        pageConfig1.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {})
}
const getList2 = () => {
  let par = {
    current: pageConfig2.currentPage,
    size: pageConfig2.pageSize,
    processDefKey: processDefKey.value,
    activityDefKey: activityDefKey.value,
    startTime: state.query.startTime,
    endTime: state.query.endTime,
    startDeptId: state.query.startDeptId,
    groupByDateType: state.query.groupByDateType,
    startId: state.query.startId,
  }
  apiQueryProccessActivityTask(par)
    .then((res) => {
      if (res.data.success) {
        nodeShow.value = true
        nodeList.value = res.data.data.result
        pageConfig2.pageSize = Number(res.data.data.size)
        pageConfig2.total = Number(res.data.data.count)
      } else {
      }
    })
    .catch((error: any) => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const handleCurrentChange1 = (e) => {
  pageConfig1.currentPage = e
  getList1()
}
const handleCurrentChange2 = (e) => {
  pageConfig2.currentPage = e
  getList2()
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiQueryProccessCount(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const processloadMore = () => {
  if (loadMoreEnd.value && processPage.value > 1) return
  processPage.value++
  getQueryAll()
}
const getQueryAll = () => {
  let par = {
    current: processPage.value,
    size: 10,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        // processArr.value = res.data.data.result.map((v) => {
        //   return {
        //     label: `${v.processDefinitionKey} - ${v.processDefinitionName}`,
        //     value: v.processDefinitionKey,
        //   }
        // })
        processArr.value = processArr.value.concat(res.data.data.result)
        if (processPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryAll() //查询流程名称
  getQueryDept()
  getQueryUser()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()//初始化不掉数据
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
